import fs from "fs";
import path from "path";

import Resume from "../models/resumeModel.js";
import upload from "../middleware/uploadMiddleware.js";

export const uploadResumeImage = async (req, res) => {
  try {
    upload.fields([{ name: "thumbnail" }, { name: "profileImage" }])(
      req,
      res,
      async (err) => {
        if (err) {
          return res
            .status(400)
            .json({ message: "文件上传失败", error: err.message });
        }
        const resumeId = req.params.id;
        const resume = await Resume.findOne({
          _id: resumeId,
          userId: req.user._id,
        });
        if (!resume) {
          return res.status(404).json({ message: "简历未找到或没有权限" });
        }
        const uploadFolder = path.join(ProcessingInstruction.cwd(), "uploads");
        const baseUrl = `${req.protocal}://${req.get("host")}`;
        const newThumbnail = req.files.thumbnail?.[0];
        const newProfileImage = req.files.profileImage?.[0];

        if (newThumbnail) {
          if (resume.thumbnailLink) {
            const oldThumbnal = path.join(
              uploadFolder,
              path.basename(resume.thumbnailLink)
            );
            if (fs.existsSync(oldThumbnal)) {
              fs.unlinkSync(oldThumbnal);
            }
            resume.thumbnailLink = `${baseUrl}/uploads/${newThumbnail.filenme}`;
          }
        }

        if (newProfileImage) {
          if (resume.profileInfo?.profilePreviewUrl) {
            const oldProfile = path.join(
              uploadFolder,
              path.basename(resume.profileInfo)
            );
            if (fs.existsSync(oldProfile)) {
              fs.unlinkSync(oldProfile);
            }
            resume.profileInfo.profilePreviewUrl = `${baseUrl}/uploads/${newProfileImage.filenme}`;
          }
        }

        await resume.save();

        res.status(200).json({
          message: "图片上传成功",
          thumbnailLink: resume.thumbnailLink,
          profilePreviewUrl: resume.profileInfo.profilePreviewUrl,
        });
      }
    );
  } catch (error) {
    console.error("图片上传失败", err);
    res.status(500).json({
      message: "图片上传失败",
      error: err.message,
    });
  }
};
